from flask import Blueprint, request
from models import File
from exts import db, get_time
import os
import time

bp = Blueprint("file", __name__, url_prefix="/file")


@bp.route('/upload', methods=['GET', 'POST'])
def upload():
    uploaded_file = request.files.get('file')
    print(uploaded_file)

    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(suffix, "").replace("\\", "").replace("/", "")
    basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "upload", filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(basedir, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    size = os.path.getsize(uploaded_file_path)

    if size > 1000000000:
        file_size = f"{size / 1000000000} GB"
        print(size / 1000000000, "GB")
    elif size > 1000000:
        file_size = f"{size / 1000000} MB"
        print(size / 1000000, "MB")
    else:
        file_size = f"{size / 1000} KB"
        print(size / 1000, "KB")

    big_data = File(filename=filename,
                    path="/" + new_dir.replace("\\", "/"),
                    time=get_time(),
                    size=file_size)

    db.session.add(big_data)
    db.session.commit()
    return "success"
